package com.video.listener;

import com.qf.entity.RunLogEntity;
import com.rabbitmq.client.Channel;
import com.video.service.IRunLogService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class RabbitMsgListener {

    @Autowired
    private IRunLogService runLogService;

    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(name = "runlog_exchange", type = "fanout"),
            value = @Queue(name = "runlog_queue", durable = "true")))
    public void msgHandler(RunLogEntity runLogEntity, Message message, Channel channel){

        try {

            //将消息保存到elasticsearch中
            runLogService.insertDoc(runLogEntity);

            //确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
            //拒绝消息
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }
}
